//
//  HSLoginController.swift
//  HomeSchoolDemo
//
//  Created by Mac on 16/9/29.
//  Copyright © 2016年 chendong. All rights reserved.
//

import UIKit
import SVProgressHUD

class HSLoginController: UIViewController {
    //登录按钮属性
    @IBOutlet weak var loginButton: UIButton!
    //密码输入框
    @IBOutlet weak var loginPassWordTF: UITextField!
    //用户名输入框
    @IBOutlet weak var loginAccountTF: UITextField!
    //菊花指示器
    lazy var activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //添加活动指示器
        activity.center = view.center
        activity.color = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
        view.addSubview(activity)
    }
    
    //数据请求
    func downloadData() {
        //拼接地址
        let urlStr = baseURLStr! + "ZH-schoolname-S-login"
        //参数字典
        let param = ["code":"5105","password":"123456"]
        HSNetworkTools.shared.downloadData(url: urlStr, parameters: param) { (data, error) in
            print(data,error)
            if error != nil {
                print("数据请求失败")
                return
            }
            print(data)
        }
        
    }
    
    //设置UI
    fileprivate func setupUI(){
        //设置圆角半径
        loginButton.layer.cornerRadius = 5
        //设置边框
        loginButton.layer.borderColor = UIColor.gray.cgColor
        loginButton.layer.borderWidth = 1
        //设置输入框左边视图
        loginAccountTF.leftView = setupLeftView(imageName: "icon_user")
        loginAccountTF.leftViewMode = .always
        
        loginPassWordTF.leftView = setupLeftView(imageName: "icon_password")
        loginPassWordTF.leftViewMode = .always
        
    }
    
    //左边视图
    fileprivate func setupLeftView(imageName:String) -> UIView {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        ///第一张视图
        let firstV = UIImageView(image: UIImage(named: imageName))
        firstV.center = CGPoint(x: firstV.bounds.width/2+10, y: 22)
        bgView.addSubview(firstV)
        //第二张图片
        let towV = UIImageView(image: UIImage(named: "line_edit_sep"))
        towV.center = CGPoint(x: firstV.frame.maxX + firstV.bounds.width/2+10, y:22 )
        bgView.addSubview(towV)
        
        return bgView
        
    }

    
    
    //登录按钮监听回调方法
    @IBAction func loginBtnClicked(_ sender: UIButton) {
        //先要判断用户是否已经设置服务器IP地址
        if baseURLStr == nil || baseURLStr! == "zao/interface/"{
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.showInfo(withStatus: "请先设置学校Ip地址")
            print("请先设置学校Ip地址")
            return
        }
        
        guard let acc = loginAccountTF.text, acc != "" else {
            //提醒用户账号不能为空
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.showInfo(withStatus: "账号不能为空")
            print("账号不能为空")
            return
        }
        guard let pass =  loginPassWordTF.text, pass != "" else {
            SVProgressHUD.setMinimumDismissTimeInterval(2)
            SVProgressHUD.showInfo(withStatus: "密码不能为空")
            print("密码不能为空")
            return
        }
        
        
        
        //拼接地址
        let urlStr = baseURLStr! + "ZH-schoolname-S-login"
        //参数字典
        let param = ["code":acc,"password":pass]
        HSNetworkTools.shared.downloadData(url: urlStr, parameters: param) {[weak self] (data, error) in
            print(data,error)
            if error != nil {
                SVProgressHUD.setMinimumDismissTimeInterval(2)
                SVProgressHUD.showInfo(withStatus: "网络请求失败，请检查IP地址")
                print("数据请求失败")
                return
            }
            //获得返回数据
            guard let dict = data as? NSDictionary else{
                return
            }
            let result = dict["result"] as! Int
            switch result{
            case 0:
                print(saveUserfoPath)
                //保存数据
                //获得保存数据路径
                dict.write(toFile: saveUserfoPath, atomically: true)
                self?.activity.stopAnimating()
                //获得下一个页面控制器
                UIApplication.shared.keyWindow?.rootViewController = HSDrawerController()
                //记录登录状态
                UserDefaults.standard.set(true, forKey: isLogin)
                
            case 1:
                SVProgressHUD.setMinimumDismissTimeInterval(2)
                SVProgressHUD.showInfo(withStatus: "账号或密码错误")
                print("账号或密码错误")
            default:
                break
            }
        
    }
}
    //设置按钮监听回调方法
    @IBAction func loginSetBtnClicked(_ sender: UIButton) {
        //弹窗输入
        let alertVc = UIAlertController(title: "请输入学校服务器的IP地址", message: nil, preferredStyle: .alert)
        //添加文本输入框
        alertVc.addTextField { (textF) in
            textF.placeholder = "IP地址"
            textF.borderStyle = .none
            textF.textAlignment = .center
            //获得保存的内容，显示
            let saveIp = UserDefaults.standard.value(forKey: cd_ipKey)
            textF.text = saveIp as? String
        }
        //确定按钮
        alertVc.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            print("确定按钮")
            //获得输入框的内容
            let IPText = alertVc.textFields?[0].text
            //保存字符串
            UserDefaults.standard.set(IPText, forKey: cd_ipKey)
        }))
        //取消按钮
        alertVc.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alertVc, animated: true, completion: nil)
    }
    
    ///调整状态栏模式
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }

    
    
    
}

extension HSLoginController{
    //回收键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}
